import Mocha from '../../modules/mocha.js';
import Util from '../../modules/util.js';
import RTLog from '../../modules/rt_log.js';
const App = getApp();

Page({
    data: {
        result: '',
        imageLoading: false,
        themeColor: getApp().globalData.themeColor,
        customErrorPopup: false,
        errContext: ''
    },
    onLoad(options) {
        this.setData({
            result: decodeURIComponent(options.url),
            imageLoading: true
        });

        Mocha.getConfig()
            .then((cfg) => {
                this.setData({
                    themeColor: cfg.theme.main_color
                });

                wx.setNavigationBarColor({
                    frontColor: cfg.theme.navibar_text_color || '#000000',
                    backgroundColor: '#F5F5F5'
                });
            })
    },
    onSaveImage() {
        Util.saveImage(this.data.result, '保存完成')
            .then(() => {
                getApp().mox.stat('share page save_image success');
            })
            .catch((err) => {
                if (err?.errMsg?.includes('deny')) {
                    getApp().mox.stat(`share page save_image fail: user refuse auth`);
                    RTLog.error('share page save_image fail：', 'user refuse auth');
                } else {
                    // getApp().mox.stat(`share page save_image fail:${err.errMsg || err.msg || '未知错误'}`);
                    getApp().mox.stat(`share page save_image fail`);
                    RTLog.error('share page save_image fail：', err.errMsg || err.msg || '未知错误');
                }
            });
    },
    onShareAppMessage: function () {
        getApp().mox.stat('share page share_result');

        return {
            title: App.globalData.productInfo.h5_config.title,
            imageUrl: App.globalData.productInfo.h5_config.cover,
            path: `/pages/product/product?mpid=${this.options.mpid}`
        };
    },
    onLoadImageFinish() {
        this.setData({
            imageLoading: false
        });
        getApp().mox.stat('share page load_image success');
    },
    onLoadImageFail(evt) {
        let { errMsg = '未知错误' } = evt.detail;
        this.setData({
            errContext: '图片加载失败，请稍后重试~',
            customErrorPopup: true
        });
        // getApp().mox.stat(`share page load_image fail: ${errMsg}`);
        getApp().mox.stat(`share page load_image fail`);
        RTLog.error('share page load_image fail：', errMsg);
    },
    onPreviewImage() {
        wx.previewImage({
            urls: [this.data.result]
        });
        getApp().mox.stat('share page preview_image');
    }
});
